package study;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;

public class DecodeString {
    public static String decodeString(String str) {
        Deque<Character> stack = new ArrayDeque<>();
        Deque<Character> stackChars = new ArrayDeque<>();
        HashMap<Character, Character> numMap = new HashMap<>();
        Character[] nums = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
        for (int i = 0; i < nums.length; i++) {
            numMap.put(nums[i], nums[i]);
        }
        char[] chars = str.toCharArray();
        StringBuilder ret = new StringBuilder();
        for (int i = 0; i < chars.length; i++) {
            if (numMap.containsKey(chars[i])) {
                stack.push(chars[i]);
                continue;
            }
            if (chars[i] == ']') {
                int side = stack.pop() - '0';
                StringBuilder temp = new StringBuilder();
                while (stackChars.peek() != '[') {
                    temp.append(stackChars.pop());
                }
                if (stackChars.peek() == '[') {
                    stackChars.pop();
                }
                char[] charArr = temp.toString().toCharArray();
                for (int k = 0; k < side; k++) {
                    for (int j = temp.length() - 1; j >= 0; j--) {
                        stackChars.push(charArr[j]);
                    }
                }
                continue;
            }
            stackChars.push(chars[i]);
        }
        while (!stackChars.isEmpty()) {
            ret.append(stackChars.pop());
        }
        return ret.reverse().toString();
    }

    public static void main(String[] args) {
        String test = "a3[a2[c]]";
        System.out.println(decodeString(test));
    }
}
